package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.qf.pojo.OrderDetail;
import com.qf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Package: com.qf.controller
 * @ClassName: PyaController
 * @Author: lmr
 * @CreateTime: 2021/9/12 22:00
 * @Description:支付
 * @Version: 1.0
 */
@RestController
public class PyaController {
    @Autowired
    private OrderService orderService;
    private OrderDetail orderDetail;

    @RequestMapping("/pay")
    public void pay(HttpServletRequest httpRequest,
                    HttpServletResponse httpResponse, @RequestParam("oidList") List<String> oidList) throws IOException, AlipayApiException {
        //构造支付宝证书的client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置请求的支付宝路径(对应的支付宝网关)
        certAlipayRequest.setServerUrl("https://openapi.alipaydev.com/gateway.do");
        //设置当前的支付宝appid
        certAlipayRequest.setAppId("2016091600521312");//改成自己的appid
        //设置应用私钥 应用私钥在支付宝开放平台助手生成crt时自动生成
        certAlipayRequest.setPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHJUKsbjQ8xIuY3JYrpEB+vN0HlTx+CPtNX3rBSAd6umsA7DNVu6P1BZVCQ66rfudIaBDYTEEpEFUgNtjgRbloL5AdBTExj8GP6vur7Ksu6YzfOK0jXp/WuTWKJQ0/3OhkLbO1N6b0EfEPi0mlwqTKSI0ZbjrL86bbC3z4jScMpk4OQZy4T7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v6QC0uLEXRm/0FoeazJc7+ZDGzPTRfaq1XrsLK2HXodoqQDqL4gxcVFzSSPl3/v7veLCMTEwRWrwYyt9ZXk9pO+6mYX77x+nuYFmJm/GQCt8vv5Un5ZI3JxO40oqO5eQKBgCeE3BjCc6loCk5RrWgRaH5X2wuprM9ZP8hS0XzBSovwNNkw80sl5b2rZmijZYcELNTxR7Lk/Ax8wKiGAJrotZiyDVmZoReTTvxXNMQPfOt+t/pNZGV/ivvzPVfIlpM547OUC4ksh+SeEJJ27FWmprttIiSkwfcRwERIsXfHLAa3");
        //设置格式化方式
        certAlipayRequest.setFormat("json");
        //设置编码格式
        certAlipayRequest.setCharset("utf-8");
        //设置加密的方式
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥的绝对路径-->下载的公钥证书(改成自己的路径)
        certAlipayRequest.setCertPath("C:\\Users\\12606\\Desktop\\支付crt\\appCertPublicKey_2016091600521312.crt");
        //设置支付宝公钥的绝对路径-->下载的公钥证书
        certAlipayRequest.setAlipayPublicCertPath("C:\\Users\\12606\\Desktop\\支付crt\\alipayCertPublicKey_RSA2.crt");
        //设置支付宝根的绝对路径-->下载的公钥证书
        certAlipayRequest.setRootCertPath("C:\\Users\\12606\\Desktop\\支付crt\\alipayRootCert.crt");
        //创建默认的支付宝客户端
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        // new AlipayTradeAppPayRequest() 这个模型是app的请求方式
        //创建电脑网站支付的请求客户端
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置支付宝成功后的同步回调//内网穿透
        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        //设置支付宝成功后的异步回调.//内网穿透
        alipayRequest.setNotifyUrl("http://4318345v0p.eicp.vip/returnUrl");
        // AlipayTradeAppPayModel 这个模型是app的请求模型
        //AlipayTradePagePayModel 这个模式时web请求模型
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //获取订单详情
        //System.out.println(oidList+"===");
        List<OrderDetail> orderDetailList = orderService.findOrderDetail(oidList);
        orderDetail = orderDetailList.get(0);
        //将订单信息存入session中
        //httpRequest.getSession().setAttribute("orderDetail",orderDetail);
        //System.out.println(orderDetail +"-----------");
        model.setSubject(orderDetail.getGname());//主题//商品名称
        model.setBody(orderDetail.getExplain());//请求体//商品描述：
        model.setOutTradeNo(orderDetail.getOid());
        //超时时间
        model.setTimeoutExpress("30m");
        //价格
        model.setTotalAmount(String.valueOf(orderDetail.getPrice()));
     /*   if (oidList != null) {
            List<OrderDetail> orderDetailList =orderService.findOrderDetail(oidList);
            System.out.println(orderDetailList+"===============");
            for (OrderDetail orderDetail : orderDetailList) {
                model.setSubject(orderDetail.getGname());//主题//商品名称
                model.setBody(orderDetail.getExplain());//请求体//商品描述：
                //model.setGoodsDetail(orderDetailList);
                //out_trade_no 订单号，客户自定义
                model.setOutTradeNo(orderDetail.getOid());
                //超时时间
                model.setTimeoutExpress("30m");
                //价格
                model.setTotalAmount(String.valueOf(orderDetail.getPrice()));
            }*/
        //app支付时productCode参数的值为 "QUICK_MSECURITY_PAY"；
        //web支付时为 FAST_INSTANT_TRADE_PAY
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        //填充业务参数
        alipayRequest.setBizModel(model);

        String form = "";
        try {
            //发起请求
            AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(alipayRequest);
            //获取返回参数
            form = alipayTradePagePayResponse.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 支付成功后的回调路径
     *
     * @param request
     * @param httpResp
     * @throws AlipayApiException
     */
    @RequestMapping("/returnUrl") //配置需与你的请求支付中的return_url中的路径保持一致
    public void returnUrl(HttpServletRequest request, HttpServletResponse httpResp) throws AlipayApiException {
        Map<String, String> stringStringMap = convertRequestParamsToMap(request);
        //调用SDK公钥私钥验签方式
        // boolean  signVerified = AlipaySignature.rsaCheckV1(stringStringMap, "alipay_public_key", "utf-8", "RSA2");
        //证书回调验签方式(选一种设置公钥的路径)
        boolean signVerified = AlipaySignature.rsaCertCheckV1(stringStringMap, "C:\\Users\\12606\\Desktop\\支付crt\\alipayCertPublicKey_RSA2.crt", "utf-8", "RSA2");  //调用SDK验证签名

        if (signVerified) {
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，
            //  校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //  stringStringMap里存放的是支付订单时支付宝返回的相关的东西
            System.out.println(orderDetail+"=============----------");
            String oid = orderDetail.getOid();
            Integer num = orderService.update(oid);
            System.out.println(num);
            System.out.println(stringStringMap);
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }
}
